package ru.amse.baltijsky.javascheme.frames.image;

import ru.amse.baltijsky.javascheme.exporter.image.IImageExporter;
import static ru.amse.baltijsky.javascheme.util.VisConst.PREFERRED_SCROLLER_HEIGHT;
import static ru.amse.baltijsky.javascheme.util.VisConst.PREFERRED_SCROLLER_WIDTH;

import javax.swing.*;
import java.awt.*;

/**
 * A frame that shows the schema tree exported to image on the screen.
 */
public class ImageFrame extends JFrame {
    private ImageViewPanel viewPanel;

    /**
     * Runs the GUI thread with the frame.
     *
     * @param exporter the exporter of the image that will be shown in the frame
     */
    public static void runFrame(final IImageExporter exporter) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ImageFrame frame = new ImageFrame();
                frame.createScrollableViewPanel(exporter);
                frame.showFrame();
            }
        });
    }

    /**
     * Creates a frame.
     */
    private ImageFrame() {
        super("JavaScheme");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    /**
     * Creates a panel in the frame that shows the image of the schema tree as exported by the specified image exporter.
     *
     * @param exporter the image exporter
     */
    private void createScrollableViewPanel(IImageExporter exporter) {
        viewPanel = new ImageViewPanel(exporter);
        JScrollPane scroller = new JScrollPane(viewPanel);
        scroller.setPreferredSize(new Dimension(PREFERRED_SCROLLER_WIDTH, PREFERRED_SCROLLER_HEIGHT));
        add(scroller);
    }

    private void createViewPanel(IImageExporter exporter) {
        viewPanel = new ImageViewPanel(exporter);
        add(viewPanel);
    }

    /**
     * Shows the resulting frame onto the screen.
     */
    private void showFrame() {
        pack();
        setVisible(true);
        viewPanel.start();
    }
}